package validators;

import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpSession;

import controllers.LocaleController;
import beans.RepositoryBeanRemote;

/**
 * @author Zsolt
 */
@ManagedBean
public class RepNameValidator implements Validator{

	@EJB 
	private RepositoryBeanRemote rb;
	/**
	 * Description: method that validates repositoryName introduced by Admin
	 * @author Zsolt
	 * @param FacesContext, UIComponent, Object (contains the repName)
	 */
	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		String enteredName = (String) value;
		Pattern p = Pattern.compile("[a-zA-Z0-9]*");
		Matcher m = p.matcher(enteredName);
		boolean matchFound = m.matches();

		//internationalization
		HttpSession session = (HttpSession)
				FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		LocaleController language = (LocaleController) session.getAttribute("language");
		String messageBundleName = "errorMessages.errors";
		if (language.getLanguage()=="ro"){
			messageBundleName += "_ro";
		}
		else if (language.getLanguage()=="hu"){
			messageBundleName += "_hu";
		}
		else if (language.getLanguage()=="de"){
			messageBundleName += "_de";
		}
		ResourceBundle messageBundle = ResourceBundle
				.getBundle(messageBundleName);

		if (enteredName.equals("")||(enteredName==null)){
			FacesMessage message = new FacesMessage();
			message.setDetail(messageBundle.getString("repositoryNameEmpty"));
			message.setSummary(messageBundle.getString("repositoryNameEmpty"));
			throw new ValidatorException(message);
		} else {
			if (!matchFound){
				FacesMessage message = new FacesMessage();
				message.setDetail(messageBundle.getString("repositoryNameContainsUnapprovedCharacters"));
				message.setSummary(messageBundle.getString("repositoryNameContainsUnapprovedCharacters"));
				throw new ValidatorException(message);
			} else { 
				if ((rb.existsNameInDB(enteredName))){
					FacesMessage message = new FacesMessage();
					message.setDetail(messageBundle.getString("repositoryNameIsAlreadyInDatabase"));
					message.setSummary(messageBundle.getString("repositoryNameIsAlreadyInDatabase"));
					throw new ValidatorException(message);
				}
			}

		}
	}

}
